package org.liuqm.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.liuqm.pojo.vo.SysUserVo;
import org.liuqm.service.ISysUserService;
import org.liuqm.service.impl.SysUserServiceImpl;
import org.liuqm.utils.response.AjaxResult;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

// 用于处理登录相关的请求
@WebServlet(name = "SysUserServlet", urlPatterns = "/sysUser")
public class SysUserServlet extends HttpServlet {


    private ISysUserService sysUserService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        sysUserService = new SysUserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、创建out对象
        PrintWriter out = response.getWriter();
        // 2、获取从小程序端请求过来的参数
        // request.getReader()用于获取BufferedReader对象，用来读取从小程序请求过来的参数
        // 调用lines()方法可以将一个BufferedReader对象转换为一个Stream对象。
        // 再调用collect()以及Collectors.joining()将传递过来的请求参数使用逗号拼接成字符串
        String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        // 将JSON字符串转换成JSONObject对象
        JSONObject object = JSONUtil.parseObj(params);
        // 从JSONObject对象中获取key为opr所对应的值，再转换成String类型。
        String op = object.get("op", String.class);
//        String userId = object.get("uid", String.class);
        String userId="1";

        AjaxResult result = null;

        // 修改会员信息
        SysUserVo sysUserVo = sysUserService.findUserById(userId);
        if (sysUserVo != null) {
            result = AjaxResult.success("获取用户信息成功!", sysUserVo);
        } else {
            result = AjaxResult.error("获取用户信息失败!");
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
